package com.like.banzipao.server

import com.like.banzipao.server.db.DatabaseHelper
import com.like.banzipao.server.model.RESULT_ERROR
import com.like.banzipao.server.model.RESULT_OK
import com.like.banzipao.server.model.ResultModel
import com.like.banzipao.server.model.User
import com.like.banzipao.server.model.users
import io.ktor.http.content.PartData
import io.ktor.http.content.forEachPart
import io.ktor.server.application.ApplicationCall
import io.ktor.server.auth.UserIdPrincipal
import io.ktor.server.auth.principal
import io.ktor.server.request.receiveMultipart
import io.ktor.server.response.respond
import org.ktorm.dsl.eq
import org.ktorm.entity.find

suspend fun ApplicationCall.getFormItemMap(): Map<String, String> {
    val valueMap = mutableMapOf<String, String>()
    val multipart = receiveMultipart()
    multipart.forEachPart {
        if (it is PartData.FormItem) {
            println("${it.name} = ${it.value}")
            val name = it.name
            if (name != null) {
                if (valueMap.containsKey(name)) {
                    // 兼容传递过来的多个值，比如 IntArray
                    valueMap[name] = valueMap[name] + ",${it.value}"
                } else {
                    valueMap[name] = it.value
                }
            }
        }
    }
    return valueMap
}

fun ApplicationCall.getCurrentUser(): User? {
    val userName = principal<UserIdPrincipal>()?.name
    if (userName.isNullOrEmpty()) {
        return null
    }
    return DatabaseHelper.database.users.find { it.name eq userName }
}

suspend fun <T> ApplicationCall.respondSuccess(data: T) {
    respond(ResultModel(code = RESULT_OK, data = data))
}

suspend fun ApplicationCall.respondError(message: String?, code: Int = RESULT_ERROR) {
    respond(ResultModel<Unit>(code = code, message = message ?: "unknown error"))
}